/** 
 * ContentDirectory -Implements the ContentDirectory Service
 *
 * @author Scot McSweeney-Roberts
 * @version 0.1
 * 
 */

package uk.co.sheitgeist.fums.server.upnp

import uk.co.sheitgeist.fums.server.content.context.*
//import uk.co.sheitgeist.fums.server.content.filesystem.*

import uk.co.sheitgeist.fums.server.upnp.adaptors.*

import com.cidero.upnp.*;
import org.cybergarage.upnp.Action;

import java.util.logging.Logger;

public class ContentDirectory extends com.cidero.upnp.ContentDirectory {

	private static Logger logger = Logger.getLogger("uk.co.sheitgeist");
	
	private static final String ROOT_ID = "0"

	MediaServer device;
	CDSStorageFolder rootFolder; 

	def contentContexts = [:]

	public ContentDirectory(MediaServer device) {
		super(device)
		this.device = device
		initializeStateVariables()

	}
  
	public void initializeStateVariables() {
		setStateVariable("SystemUpdateID", "1" );
	}


	public addContentContext(ContentContext contentContext) {
		this.contentContexts[contentContext.name] = contentContext
	}

	public boolean actionBrowse(Action action) {
		logger.fine "Action: Browse"
		String browseFlag = action.getArgumentValue("BrowseFlag");		 
		boolean result = false;

		switch (browseFlag) {
			case "BrowseDirectChildren":
				result = browseDirectChildren(action)
				break
			case "BrowseMetadata":
				result = browseMetadata(action)
				break

		}
		return result
	}

	public boolean browseDirectChildren(Action action) {
		String filter = action.getArgumentValue("Filter");
		int startingIndex = action.getArgumentIntegerValue( "StartingIndex" );
		int requestedCount = action.getArgumentIntegerValue( "RequestedCount" );
		String objectID = action.getArgumentValue("ObjectID");
		String sortCriteria = action.getArgumentValue("SortCriteria");
		if( sortCriteria == null ) sortCriteria = "";

		CDSObjectList upnpObjList = null		

		if (objectID == ContentDirectory.ROOT_ID) {
			//this takes care of a request to browse the "root"
			//what we do here is add each store to the child object list
			
			upnpObjList = new CDSObjectList()
			
			contentContexts.each { name, contentContext ->
				def contentContextAdaptor = new ContentContextAdaptor(contentContext)
				upnpObjList.add(contentContextAdaptor.root)
			}

		} else {
			/*
			 * browse a particular child node
			 *
			 * this implementation assumes that the object is context:rest_of_id
			 * so we get the correct context from the object id, create a content context
			 * adaptor and then pass in the requested object to browse to the adaptor
			 *
			 * I can't help but wonder if it would be better to change the context holding
			 * to an adaptor holding. This will do for now though.
			 *
			 *
			*/
			//logger.info "Object ID: ${objectID}"
			String context = objectID.split(":")[0]
			ContentContext contentContext = contentContexts[context]
			def contentContextAdaptor = new ContentContextAdaptor(contentContext)
			upnpObjList = contentContextAdaptor.getDirectChildren(objectID)
		}
		
		int[] numMatches =[0];
		String result = CDS.toDIDL(upnpObjList, filter,
                           startingIndex, requestedCount, numMatches,
                           null, null)
		
		action.setArgumentValue( "NumberReturned", numMatches[0] );
		action.setArgumentValue( "TotalMatches", upnpObjList.size() );
		action.setArgumentValue( "Result", result );
		action.setArgumentValue( "UpdateID", "100" );
		
		return true

	}

	public boolean browseMetadata(Action action) {
		logger.info "browseMetadata"
		String filter = action.getArgumentValue("Filter");
		int startingIndex = action.getArgumentIntegerValue( "StartingIndex" );
		int requestedCount = action.getArgumentIntegerValue( "RequestedCount" );
		String objectID = action.getArgumentValue("ObjectID");
		String sortCriteria = action.getArgumentValue("SortCriteria");
		logger.info "${objectID}"
		CDSObject object
		if (objectID == ContentDirectory.ROOT_ID) {
				CDSStorageFolder folder = new CDSStorageFolder()
				folder.id = "0"
				folder.parentId = "-1"
				folder.title = "fums"
			//	folder.creator = "UNKNOWN"
				folder.searchable = false
				folder.childCount = 2
				object = folder
	
		} else {
			String context = objectID.split(":")[0]
			ContentContext contentContext = contentContexts[context]
			ContentContextAdaptor contentContextAdaptor = new ContentContextAdaptor(contentContext)
			object = contentContextAdaptor.getChild(objectID)
		}
		int[] numMatches =[0];
//		String result = CDS.toDIDL(object, filter,
//                           startingIndex, requestedCount, numMatches,
//                           null, null)

		String result = CDS.toDIDL( object, filter );
		logger.info result
		action.setArgumentValue( "NumberReturned", 1 );
		action.setArgumentValue( "TotalMatches", 1 );
		action.setArgumentValue( "Result", result );
		action.setArgumentValue( "UpdateID", "100" );

		return true

	}

}
